<script>
/**
 * @desc 收支类型 百分百 列表
 */

import TypePercentItem from '@/components/type-percent-item'
import { numberFixed } from '@/utils'

export default {
  name: 'type-percent',

  props: {
    typeIndex: {
      type: Number,
      default: 0
    },
    data: {
      type: Array,
      default: () => []
    }
  },

  components: { TypePercentItem },

  computed: {
    list() {
      /**
       * 1.过滤type
       * 2.求出总的金额
       * 3.根据type汇总
       * 4.计算百分百
       */
      let mergeArr = this.data.filter(v => v.type === this.typeIndex)
      const totalMoney = mergeArr.reduce((pre, curr) => pre + curr.money, 0)
      mergeArr = mergeArr.reduce((pre, curr) => {
        const eqIndex = pre.findIndex(item => item.way === curr.way)
        if (eqIndex !== -1) {
          pre[eqIndex].money += curr.money
          return pre
        } else {
          return [...pre, { way: curr.way, money: curr.money }]
        }
      }, [])
      mergeArr = mergeArr.map(v => ({
        ...v,
        percent: numberFixed(100 * v.money / totalMoney)
      }))
      return mergeArr
    }
  }
}
</script>

<template>
  <div :class="$sty.container">
    <type-percent-item
      :key="i"
      :money="v.money"
      :percent="v.percent"
      :typeIndex="typeIndex"
      :way="v.way"
      v-for="(v,i) in list"
    />
  </div>
</template>

<style lang="scss" module>
.container {
  padding: $content-box-padding;
  background-color: #fff;
}
</style>
